<?php
/**
 * Created by PhpStorm.
 * User: lwt
 * Date: 4/26/19
 * Time: 8:21 PM
 */

namespace app\index\model;

use think\Db;
use think\Model; 

class TracesourceModel extends Model
{
    public static function addTraceSource($data){
        $msg = Db::query('select *  from tb_de_trace_source where de_openid = ? and pc_id=?',
            [$data["de_openid"],$data["pc_id"]]);
        $isNull = true;
        if (is_array($msg)){
            $isNull = false;
        }
        if ($isNull){
            $msg = Db::table('tb_de_trace_source')->insert($data);
            return $msg;
        }else{
            Db::table('tb_de_trace_source')->where('tds_id', $msg[0]["tds_id"])->update($data);
            return 0;
        }

    }

    public static function selectAllTraceSourceById($data){
        if ($data["sc_id"] == "" || $data["sc_id"] == null) {
            $msg = array();
            $msg["code"] = 200;
            $msg["msg"] = [];
            return $msg;
        }
        $msg1 = Db::query('select *  from tb_subcode where sc_id = ?',[$data["sc_id"]]);
        if (empty($msg1)) {
            $msg = array();
            $msg["code"] = 400;
            $msg["msg"] = "商品不存在！";
            return $msg;
        }
        $msg2 = Db::query('select *  from tb_de_trace_source where pc_id = ? order by tds_time asc',[$msg1[0]["pc_id"]]);
        $msg = array();
        $msg["code"] = 200;
        $msg["sc_num"] = $msg1[0]["sc_num"];
        $msg["sc_select_time"] = $msg1[0]["sc_select_time"];
        $msg["sc_select_address"] = $msg1[0]["sc_select_address"];
        $msg["msg"] = $msg2;

        $msgUpdate = $msg1[0];
        $msgUpdate["sc_num"] = $msgUpdate["sc_num"] + 1;
        $msgUpdate["sc_select_time"] = time();
        $msgUpdate["sc_select_address"] = $data["sc_select_address"];
        Db::table('tb_subcode')->where('sc_id', $data["sc_id"])->update($msgUpdate);

        return $msg;
    }
}